# -*- encoding:utf-8 -*-
# @Time: 2022/12/25 10:42
# @Author :xibin
# @Email: xibin@maqu. com
# @File: serializers.py
# @Software: PyCharm
from rest_framework.serializers import ModelSerializer
from rest_framework import serializers
from rest_framework.fields import SerializerMethodField #通过序列化器的方法进行查询，展示出一个字段
from .models import *


class ArticleSerializer(ModelSerializer):
    user_name = serializers.CharField(source='user.username',read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatar',read_only=True) #显示用户头像，从用户的详情表里找到头像，然后展示出来
    label_name = serializers.CharField(source='label.name',read_only=True)

    class Meta:
        model = Article
        exclude = ['is_delete'] #不在前端展示的

class SonCommentSerializer(ModelSerializer):
    user_name = serializers.CharField(source='user.username',read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatar',read_only=True)
    reply_username = SerializerMethodField()

    class Meta:
        model = Comment
        exclude = ['is_delete']

    def get_reply_username(self,comment):
        #查询出被回复评论的用户的名字
        return Comment.objects.get(id=comment.reply_comment).user.username

class CommentSerializer(ModelSerializer):
    user_name = serializers.CharField(source='user.username',read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatar',read_only=True)
    sonComment = SerializerMethodField()

    class Meta:
        model = Comment
        exclude = ['is_delete']

    def get_sonComment(self,comment):  #子级评论
        serializer = SonCommentSerializer(Comment.objects.filter(parent_comment=comment.id),many=True)
        data = serializer.data
        data.reverse() #反向查询出来，因为排在前面的是最新的评论
        return data
